package com.define.ssh.action.statistical;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.define.ssh.action.admin.BaseAdminAction;
import com.define.ssh.model.Compdept;
import com.define.ssh.model.DataCount;
import com.define.ssh.model.DeptAccount;
import com.define.ssh.model.Terminal;
import com.define.ssh.model.UserInfo;
import com.define.ssh.service.CompdeptService;
import com.define.ssh.service.DataCountService;
import com.define.ssh.service.DeptAccountService;
import com.define.ssh.util.SystemUtil;

/**
 *  
 * 
 */
@ParentPackage("admin")
public class ReleaseMsgAction extends BaseAdminAction {

	@Resource(name = "dataCountServiceImpl")
	private DataCountService dataCountService;

	@Resource(name = "deptAccountServiceImpl")
	private DeptAccountService deptAccountService;

	@Resource(name = "compdeptServiceImpl")
	private CompdeptService compdeptService;
	
	private String clientType;
	private String dept;
	private String date;
	private String year;
	private String month;
	private String day;
	
	private String date2;
	private List<DeptAccount> deptList;
	private int max1 = 0;
	private int max2 = 0;
	private int type=1;

	
	
	private Integer netid;
	private List<Terminal> terminalList;
	/**
	 * 列表页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		date = sdf.format(new Date());

		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");
		date2 = sdf2.format(new Date());
		
		
		final DetachedCriteria dc = DetachedCriteria.forClass(Terminal.class);
		terminalList=this.dataCountService.findByCriteria(dc);
		

		Calendar calendar = Calendar.getInstance();
		year = calendar.get(Calendar.YEAR) + "";
		month = (calendar.get(Calendar.MONTH) +1)+"";
		day = calendar.get(Calendar.DAY_OF_MONTH)+"";

		return "releaseMsg";
	}

	public String chartData1() {
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		String sql="SELECT DATE_FORMAT(t.`datetime`,'%Y%m%d%H'),SUM(t.count)  FROM `T_DATA_COUNT` t"
				+ " WHERE 1=1 ";
		if (StringUtils.isNotBlank(date)) {
			sql=sql+" AND  DATE_FORMAT(t.`datetime`,'%Y-%m-%d')='"+date+"'";
		} else {
			sql=sql+" AND  DATE_FORMAT(t.`datetime`,'%Y-%m-%d')='"+sdf1.format(new Date())+"'";
		}
		if (StringUtils.isNotBlank(clientType)) {
			sql=sql+" AND t.`client_type`="+clientType;
		}
		if (StringUtils.isNotBlank(dept)) {
			sql=sql+" AND t.`dept`='"+dept+"'";
		}
		if(netid!=null){
			sql=sql+" AND t.`netid`="+netid;
		}
		sql=sql+" AND t.`count_type`=1 and t.`msg_type`="+type;
		sql=sql+" GROUP BY  DATE_FORMAT (t.`datetime`,'%Y-%m-%d %H') ORDER BY t.`datetime` DESC";
		System.out.println("sql========="+sql);	
		List<Object[]> list1=dataCountService.findByQuery(sql);
		  Map<String, Double> ENUMMAP = new LinkedHashMap<String, Double>();
		for (int i = 0; i < 24; i++) {
			if(i<=9)
			 ENUMMAP.put("0"+i, 0.0);
			 else
		     ENUMMAP.put(i+"", 0.0);
		}
//		List<Object[]> list1=dataCountService.findByQuery("SELECT t.`client_type`,DATE_FORMAT(t.`datetime`,'%Y-%m-%d %H'),SUM(t.count)  FROM `t_data_count` t WHERE t.`client_type`=1  AND  DATE_FORMAT(t.`datetime`,'%Y-%m-%d')='2015-01-07' GROUP BY  client_type,DATE_FORMAT(t.`datetime`,'%Y-%m-%d %H') ORDER BY t.`datetime` DESC ");
		for (int i = 0; i < list1.size(); i++) {
			Object[] obj=list1.get(i);
			String key=obj[0].toString();
			String key1=key.substring(key.length()-2, key.length());
			
			if(ENUMMAP.containsKey(key1))
				ENUMMAP.put(key1,Double.parseDouble(obj[1].toString()) );
			
			max1=max1+(int)Double.parseDouble(obj[1].toString());
		}
		System.out.println("max1=="+max1);
		final StringBuffer out = new StringBuffer();
		int i=0;
		 for (String key : ENUMMAP.keySet()) {
			   if (i == 0) {
					out.append(ENUMMAP.get(key));
				} else {
					out.append("," + ENUMMAP.get(key));
				}
			   i++;
		 }
		final StringBuffer sb = new StringBuffer();
		sb.append("{");	
		sb.append("\"data_X1\":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],");
		sb.append("\"data_Y1\":[" + out.toString() + "],");
		sb.append("\"title_X1\":\"时间（小时）\",");
		sb.append("\"max\":"+max1);
		sb.append("}");
		return ajax(JSONObject.fromObject(sb.toString()).toString());
	}
	public String chartData2() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar calendar = Calendar.getInstance();
	
		String sql="SELECT DATE_FORMAT(t.`datetime`,'%Y%m%d'),SUM(t.count)  FROM `T_DATA_COUNT` t"
				+ " WHERE 1=1 ";
		final DetachedCriteria dc = DetachedCriteria.forClass(DataCount.class);
		if (StringUtils.isNotBlank(date2)) {
			sql=sql+" AND  DATE_FORMAT(t.`datetime`,'%Y-%m')='"+date2+"'";
		} else {
			sql=sql+" AND  DATE_FORMAT(t.`datetime`,'%Y-%m')='"+sdf.format(new Date())+"'";
			
		}
		if (StringUtils.isNotBlank(clientType)) {
			sql=sql+" AND t.`client_type`="+clientType;
		
		}
		
		if (StringUtils.isNotBlank(dept)) {
			sql=sql+" AND t.`dept`='"+dept+"'";
		
		}
		
		if(netid!=null){
			sql=sql+" AND t.`netid`="+netid;
		
		}
		
		
		sql=sql+" AND t.`count_type`=1 and t.`msg_type`="+type;
		
		
		sql=sql+" GROUP BY  DATE_FORMAT (t.`datetime`,'%Y-%m-%d') ORDER BY t.`datetime` DESC";
		
		System.out.println("sql========="+sql);	
		List<Object[]> list1=dataCountService.findByQuery(sql);
		Map<String, Double> ENUMMAP = new LinkedHashMap<String, Double>();
		int daynum=this.calDayByYearAndMonth(StringUtils.isNotBlank(date2)?date2:sdf.format(new Date()));
		
		for (int i = 0; i < daynum; i++) {
			if(i<=9)
			 ENUMMAP.put("0"+i, 0.0);
			 else
		     ENUMMAP.put(i+"",0.0);
				
		}
		
//		List<Object[]> list1=dataCountService.findByQuery("SELECT t.`client_type`,DATE_FORMAT(t.`datetime`,'%Y-%m-%d %H'),SUM(t.count)  FROM `t_data_count` t WHERE t.`client_type`=1  AND  DATE_FORMAT(t.`datetime`,'%Y-%m-%d')='2015-01-07' GROUP BY  client_type,DATE_FORMAT(t.`datetime`,'%Y-%m-%d %H') ORDER BY t.`datetime` DESC ");
		for (int i = 0; i < list1.size(); i++) {
			Object[] obj=list1.get(i);
			
			String key=obj[0].toString();
			String key1=key.substring(key.length()-2, key.length());
			if(ENUMMAP.containsKey(key1))
				ENUMMAP.put(key1,Double.parseDouble(obj[1].toString()) );
			
			
		}
		
		
		final StringBuffer daysout = new StringBuffer();
		final StringBuffer out = new StringBuffer();
		int i=0;
		 for (String key : ENUMMAP.keySet()) {
			   if (i == 0) {
				   daysout.append(key);
				  out.append(ENUMMAP.get(key));
				} else {
					daysout.append("," + key);
				    out.append("," + ENUMMAP.get(key));
				}
			   
			   max2=max2+(int)Double.parseDouble(ENUMMAP.get(key).toString());
			  
			   i++;
		 }
		
		 System.out.println("max2=="+max2);
		
		
		final StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("\"data_X2\":["+daysout.toString()+"],");
		sb.append("\"data_Y2\":["+out.toString()+"],");
		sb.append("\"title_X2\":\"时间（日）\",");
		sb.append("\"max\":"+max2);
		sb.append("}");
		return ajax(JSONObject.fromObject(sb.toString()).toString());
	}

	private int calDayByYearAndMonth(String dyear_dmouth) {
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM");
		Calendar rightNow = Calendar.getInstance();
		try {
			rightNow.setTime(simpleDate.parse(dyear_dmouth));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return rightNow.getActualMaximum(Calendar.DAY_OF_MONTH);// 根据年月 获取月份天数
	}

	/**
	 * 取关联的部门数据
	 * 
	 * @return
	 */
	public String getDeptTree() {
		if(((UserInfo)this.getSession(SystemUtil.USERINFO)).getRole().getId()==1){
			return this.getDeptTreeByAdmin();
		}
		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("compdept.pid", 0);
		searchMap.put("userid", Integer.parseInt(((UserInfo)this.getSession(SystemUtil.USERINFO)).getId()+ ""));
		final List<DeptAccount> list = this.deptAccountService
				.getAllListByParameter(searchMap);
		final StringBuffer sb = new StringBuffer();
		sb.append("[");
		sb.append("{");
		sb.append("id:" + 0);
		sb.append(",name:\"全部\"");
		sb.append("}");
		if(list.size()>0){
			sb.append(",");
		}
		for (int i = 0; i < list.size(); i++) {
			final DeptAccount du = list.get(i);
			sb.append("{");
			sb.append("id:" + du.getCompdept().getId());
			sb.append(",pId:" + du.getCompdept().getPid());
			sb.append(",name:\"" + du.getCompdept().getDeptname() + "\"");
			sb.append("}");
			
			final HashMap<String, Object> subSearchMap = new HashMap<String, Object>();
			subSearchMap.put("compdept.pid", du.getCompdept().getId());
			subSearchMap.put("userid", Integer.parseInt(((UserInfo)this.getSession(SystemUtil.USERINFO)).getId()+ ""));
			final List<DeptAccount> sublist = this.deptAccountService
					.getAllListByParameter(subSearchMap);
			
			if (i != list.size() - 1||sublist.size()>0) {
				sb.append(",");
			}
			
			for (int s = 0; s < sublist.size(); s++) {
				final DeptAccount subDept = sublist.get(s);
				sb.append("{");
				sb.append("id:" + subDept.getCompdept().getId());
				sb.append(",pId:" + subDept.getCompdept().getPid());
				sb.append(",name:\"" + subDept.getCompdept().getDeptname() + "\"");
				sb.append("}");
				if (s != sublist.size() - 1||list.size()>i+1) {
					sb.append(",");
				}
			}
		}
		
		
		
		
		
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}
	
	private String getDeptTreeByAdmin(){
		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		searchMap.put("pid", 0);
		final List<Compdept> list = this.compdeptService.getAllListByParameter(searchMap);
		final StringBuffer sb = new StringBuffer();
		sb.append("[");
		sb.append("{");
		sb.append("id:" + 0);
		sb.append(",name:\"全部\"");
		sb.append("}");
		if(list.size()>0){
			sb.append(",");
		}
		for (int i = 0; i < list.size(); i++) {
			final Compdept dept = list.get(i);
			sb.append("{");
			sb.append("id:" + dept.getId());
			sb.append(",pId:" + dept.getPid());
			sb.append(",name:\"" + dept.getDeptname() + "\"");
			sb.append(",open:true");
			sb.append("}");
			
			final HashMap<String, Object> subSearchMap = new HashMap<String, Object>();
			subSearchMap.put("pid", dept.getId());
			final List<Compdept> sublist = this.compdeptService.getAllListByParameter(subSearchMap);
			
			if (i != list.size() - 1||sublist.size()>0) {
				sb.append(",");
			}
			
			for (int s = 0; s < sublist.size(); s++) {
				final Compdept subDept = sublist.get(s);
				sb.append("{");
				sb.append("id:" + subDept.getId());
				sb.append(",pId:" + subDept.getPid());
				sb.append(",name:\"" + subDept.getDeptname() + "\"");
				sb.append("}");
				if (s != sublist.size() - 1||list.size()>i+1) {
					sb.append(",");
				}
			}
			
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}
	
	public String getClientType() {
		return clientType;
	}

	public void setClientType(String clientType) {
		this.clientType = clientType;
	}

	public String getDept() {
		return dept;
	}

	public void setDept(String dept) {
		this.dept = dept;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public String getMonth() {
		return month;
	}

	public void setMonth(String month) {
		this.month = month;
	}


	public List<DeptAccount> getDeptList() {
		return deptList;
	}

	public void setDeptList(List<DeptAccount> deptList) {
		this.deptList = deptList;
	}

	public int getMax1() {
		return max1;
	}

	public void setMax1(int max1) {
		this.max1 = max1;
	}

	public int getMax2() {
		return max2;
	}

	public void setMax2(int max2) {
		this.max2 = max2;
	}

	public String getDay() {
		return day;
	}

	public void setDay(String day) {
		this.day = day;
	}

	public String getDate2() {
		return date2;
	}

	public void setDate2(String date2) {
		this.date2 = date2;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public Integer getNetid() {
		return netid;
	}

	public void setNetid(Integer netid) {
		this.netid = netid;
	}

	public List<Terminal> getTerminalList() {
		return terminalList;
	}

	public void setTerminalList(List<Terminal> terminalList) {
		this.terminalList = terminalList;
	}
	
	

}